import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";

class Service {
    instance: AxiosInstance;
    constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(config);
        this.instance.interceptors.request.use(
            function (config) {
                const token = localStorage.getItem("access_token");
                const videoToken = localStorage.getItem("video_token");
                token && (config.headers.Authorization = token);
                videoToken && (config.headers["access-token"] = videoToken);
                return config;
            },
            function (error) {
                return Promise.reject(error);
            }
        );

        // 添加响应拦截器
        this.instance.interceptors.response.use(
            function (response: AxiosResponse) {
                // if (response.data.code === 401 && response.config.url?.startsWith('/visual')) {
                //   localStorage.removeItem('access_token')
                //   localStorage.removeItem('video_token')
                //   router.replace('/')
                // }
                return response;
            },
            function (error) {
                return Promise.reject(error);
            }
        );
    }
    get(config: AxiosRequestConfig) {
        return new Promise((resolve, reject) => {
            this.instance
                .request({ ...config, method: "GET" })
                .then((res) => {
                    resolve(res.data);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
    post(config: AxiosRequestConfig) {
        return new Promise((resolve, reject) => {
            this.instance
                .request({ ...config, method: "POST" })
                .then((res) => {
                    resolve(res.data);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }

    put(config: AxiosRequestConfig) {
        return new Promise((resolve, reject) => {
            this.instance
                .request({ ...config, method: "PUT" })
                .then((res) => {
                    resolve(res.data);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }

    delete(config: AxiosRequestConfig) {
        return new Promise((resolve, reject) => {
            this.instance
                .request({ ...config, method: "DELETE" })
                .then((res) => {
                    resolve(res.data);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
}

export default Service;